<template>
  <div class="main-div">
    <Row >
      <Col span="4">

        <Tree :data="categoryData" expand="true" default-expand-all="true" @on-select-change="refreshTask"></Tree>

      </Col>
      <Col span="20">
        <Card dis-hover class="task-card">
          <div class="app-container">
            <el-row type="flex" justify="start" class="left-pad">
              <el-form :inline="true" :model="queryForm" class="demo-form-inline" label-width='80px' inline size='mini'>
                <el-form-item label="流程名称">
                  <el-input v-model="queryForm.name" clearable></el-input>
                </el-form-item>
                <el-form-item label="流程别名">
                  <el-input v-model="queryForm.modelKey" clearable></el-input>
                </el-form-item>
                <el-form-item label='状态' prop='status'>
                  <el-select v-model='queryForm.status' clearable>
                    <el-option v-for="item in statusList" :value="item.value" :label="item.label"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="search">查询</el-button>
                  <el-button type="default" @click="reset">重置</el-button>
                </el-form-item>
              </el-form>
            </el-row>
            <el-row style="margin-bottom: 10px" type="flex" justify="start">
              <el-col :span="1.5">
                <el-button type="primary" @click="openModelDialog" style="margin-top: 10px">
                  <Icon type="ios-add"/>
                  添加
                </el-button>
              </el-col>


              <el-col :span="1.5">
                <el-button type="warning" @click="openModelDiffDialog" style="margin-top: 10px">
                  <Icon type="icon-loading"/>
                  模型对比
                </el-button>
              </el-col>


              <el-col :span="1.5">
                <el-button type="success" @click="openModelUploadDialog" style="margin-top: 10px">
                  <Icon type="ios-cloud-upload" />
                  模型上传
                </el-button>
              </el-col>

              <el-col :span="1.5">
                <el-button
                  type="cyan"
                  size="mini"
                  :disabled="multiple"
                  @click="handleEs"
                >同步到ES
                </el-button>
              </el-col>

            </el-row>


            <el-row class="margin:30px;">
              <el-col>
                <el-table
                  :data="tableData"
                  size="mini"
                  style="width: 100%"
                  :height="tableHeight"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column
                    fixed="left"
                    prop="name"
                    label="名称"
                    width='180'
                  >
                  </el-table-column>
                  <el-table-column
                    prop="modelKey"
                    label="流程别名"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="status"
                    label="状态"
                  >


                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.defId==null || scope.row.defId==''" type="danger" class="tag">未发布</el-tag>
                      <el-tag v-else type="success" class="tag">已发布</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="version"
                    label="版本号"
                  >
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    width='650'
                    fixed="right"
                  >
                    <template slot-scope="scope">
                      <el-button type="text" size="small"  @click="locationUrl(scope.row.id)" >编辑</el-button>
                      <el-button type="text" @click="publishModel(scope.row.id)" size="small" >发布</el-button>
                      <el-button type="text" @click="versionManager(scope.row.id,scope.row.modelKey)" size="small"
                                 >版本管理
                      </el-button>
                      <el-button type="text" @click="viewImage(scope.row.id)" size="small" >查看流程</el-button>
                      <el-button type="text" @click="viewVar(scope.row.id)" size="small" >决策变量</el-button>
                      <el-button type="text" @click="exportModel(scope.row.id)" size="small" >导出</el-button>
                      <el-button type="text" @click="busModel(scope.row.id)" size="small" >业务设置</el-button>
                      <el-button v-if="scope.row.defId!=null && scope.row.defId!=''" type="text" @click="viewModel(scope.row.id,scope.row.modelKey)" size="small" >自动化测试</el-button>
                      <el-button type="text" @click="urgingModel(scope.row.id)" size="small" >催办</el-button>
                      <el-button type="text" @click="expireModel(scope.row.id)" size="small" >到期提醒</el-button>
                      <el-button type="text" @click="sequenceModel(scope.row.id)" size="small" >连线按钮</el-button>
                      <el-button type="text" @click="skipModel(scope.row.id)" size="small" >自动跳过</el-button>

                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
            <el-row type="flex" justify="end">
              <el-pagination
                background
                @current-change="handleCurrentChange"
                :current-page="queryForm.page"
                :page-size="queryForm.pageSize"
                layout="prev, pager, next, sizes, total, jumper"
                :total="total">
              </el-pagination>
            </el-row>

          </div>

        </Card>
      </Col>


    </Row>
    <Row>
    </Row>


    <Modal :mask-closable="false" v-model="modelerModal" fullscreen title="杰狮BPM流程设计器" @on-cancel="cancelModel" :transfer="false">
      <iframe width="100%" height='100%' style="min-height: 650px" frameborder='0' align='center' allowfullscreen='true'
              allow="autoplay" id='iframe' :src="modelerSrc"></iframe>
      <div slot="footer"></div>
    </Modal>
    <Modal :mask-closable="false"   v-model="viewImageModeler" fullscreen title="流程图" :transfer="false">
      <iframe width="100%" height='100%' frameborder='0' align='center' allowfullscreen='true' allow="autoplay"
              id='iframe2' :src="viewImageModelerTmpSrc"></iframe>
      <div slot="footer"></div>
    </Modal>
    <Modal :mask-closable="false"  v-model="code" fullscreen title="决策变量" :transfer="false">
      <el-alert type="warning" title="如果连线上配置有条件，则源节点完成的时候，必须传递这些变量。除非使用了杰狮BPM中可选路径功能。" style="margin-top: 10px;margin-bottom: 10px;"></el-alert>
      <div v-html="varHtml"></div>
      <div slot="footer"></div>
    </Modal>
    <Modal :mask-closable="false" v-model="uploadModal"  title="模型上传" @on-cancel="handleResetForm" :transfer="false">
      <Form :model="uploadForm" :label-width="80" :rules="uploadFormRuleValidate" ref="uploadForm">
        <FormItem label="名称" prop="name">
          <Input v-model="uploadForm.name"  ></Input>
        </FormItem>
        <FormItem label="别名" prop="modelKey">
          <Input v-model="uploadForm.modelKey"   ></Input>
        </FormItem>


        <FormItem prop="groupName" label="分类">
          <treeselect v-model="uploadForm.groupName"
                      :normalizer="normalizer"
                      :multiple="false"
                      @select="selectTree"
                      @input="clearOnSelect"

                      placeholder="请选择"
                      :options="categoryData"/>

        </FormItem>
        <FormItem label="描述" prop="description">
          <Input  v-model="uploadForm.description"   type="textarea" :autosize="{minRows: 2,maxRows: 5}"></Input>
        </FormItem>
        <FormItem label="上传" ><template>
          <Upload
            type="drag"
            :on-success="handleupLoadSuccess"
            :default-file-list="uploadList"
            :action="baseUploadURL">
            <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>单击或拖动文件上传</p>
            </div>
          </Upload>
        </template>

        </FormItem>


      </Form>

      <div slot="footer">


          <Button type="primary" @click="save('addForm')">确定</Button>
          <Button @click="handleResetForm('addForm')">取消</Button>
      </div>

    </Modal>

  </div>


</template>

<script>
  import {getTaskData, getTaskChartData, getBpmnModelCategory, getModelerJson, publishModel, getVar,uploadSaveModel,exportModelById,ipLog} from "@/api/analy";
  import {codemirror} from 'vue-codemirror'
  import "codemirror/theme/ambiance.css";  // 这里引入的是主题样式，根据设置的theme的主题引入，一定要引入！！
  require("codemirror/mode/javascript/javascript"); // 这里引入的模式的js，根据设置的mode引入，一定要引入！！
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: 'Task',
    components: {
    codemirror,Treeselect
    },

    data() {
      var checkKey = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('别名不能为空'));
        }
        var PLACEHOLDER_REGEX = /\$\{([^}]*)\}/g;
        var SPACE_REGEX = /\s/;
        value=value.replace(PLACEHOLDER_REGEX, '$1');
        if (SPACE_REGEX.test(value)) {
          return callback(new Error('Key不能包含空格'));

        }
        var ID_REGEX = /^[a-z_][\w-.]*$/i;
        var QNAME_REGEX = /^([a-z][\w-.]*:)?[a-z_][\w-.]*$/i;

        if (!ID_REGEX.test(value)) {
          if (QNAME_REGEX.test(value)) {
            return callback(new Error('别名不能包含前缀.'));
          }
          return callback(new Error('别名必须是一个有效的QName'));
        }
        return  callback();
      };
      return {
        multiple: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        multipleSelection: [],
        uploadFormRuleValidate: {
          name: [
            {required: true, message: '    ', trigger: 'blur'}
          ],
          groupName: [
            {required: true, message: '    ', trigger: 'blur'}
          ],
          modelKey: [
            {required: true, message: '    ', trigger: 'blur'},
            { validator: checkKey, trigger: 'blur' }
          ]
        },
        baseUploadURL: process.env.VUE_APP_BASE_BPM_API+"/a1bpmn/api/upload/model",
        uploadForm: {
          name: "",
          modelKey: '',
          id: "",
          description: '',
          typeId: null,
          groupName: null,
        },
        tableData: [],
        tableHeight: 450,
        queryDate: [],
        total: 0,
        chartVisible: false,
        code: false,
        varHtml: "",
        modelerModal: false,
        uploadModal: false,
        viewImageModeler: false,
        chartData: {},
        baseURL: process.env.VUE_APP_BASE_BPM_API,
        modelerSrc: process.env.VUE_APP_BASE_BPM_API + "diagram/index.html",
        viewImageModelerSrc: process.env.VUE_APP_BASE_BPM_API + "view/def.html?&modelId=",
        viewImageModelerTmpSrc: "",
        shopName: [],
        statusList: [
          {label: "未发布", value: "0"},
          {label: "已发布", value: "1"},
        ],
        queryForm: {
          name: "",
          modelKey: "",
          createTime: "",
          page: 1,
          limit: 10,
          pageSize: 10,

          status: '',
          whereSql: "",
          type: 5,
          typeKey: ""
        },
        categoryData: [],
        uploadList: [],
      }
    },
    mount() {
      this.getData()
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
    },
    created() {

      this.getData()
      var threshold=160;
      var count=1;
      setInterval(function(){

      })
    },
    methods: {
      handleEs(){
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.ids = val.map(item => item.id)
        this.single = val.length !== 1
        this.multiple = !val.length
      },
      recursionWindow:function(){
      },
      handleResetForm:function(){
        this.uploadForm.name="";
        this.uploadForm.modelKey="";
        this.uploadForm.id="";
        this.uploadForm.description="";
        this.uploadForm.typeId=null;
        this.uploadForm.groupName=null;
        this.uploadList=[]
        this.uploadModal=false
      },
      save: function () {
        this.$refs['uploadForm'].validate((valid) => {
          if (valid) {
            var formData = this.uploadForm;
            if (this.uploadList.length==0){
              this.$message({"duration":800,message:'模型文件必须上传',type:'warning',customClass:'zZindex'});

              return
            }
            if (formData.id){
              uploadSaveModel(this.uploadForm).then((response) => {
                if (response.code == 0) {
                  this.uploadModal=false;
                  this.handleResetForm();
                  this.locationEditUrl(response.data.id)

                }else{
                  this.$message({"duration":800,message:response.msg,type:'warning',customClass:'zZindex'});


                }

              })

            } else{
              uploadSaveModel(formData).then((response) => {
                if (response.code == 0) {

                  // 调用全局挂载的方法
                  this.$store.dispatch('tagsView/delView', this.$route)
                  // 返回上一步路由
                  this.$router.go(-1)
                }

              })
            }




          } else {
            this.$message({"duration":800,message:'表单校验不通过',type:'warning',customClass:'zZindex'});

            return
          }


        })
      },
      handleupLoadSuccess (res, file) {
        file.url = res.data;
        this.uploadForm.id=res.id
        this.uploadList=[];
        this.uploadList.push(file);
        this.uploadForm.photo= file.url
      },

      //后台返回的数据如果和VueTreeselect要求的数据结构不同，需要进行转换
      normalizer(node) {
        //去掉children=[]的children属性
        if(node.children && !node.children.length){
          delete node.children;
        }
        return {
          id: node.title,
          label: node.title,
          children: node.children
        }
      },
      selectTree: function (node, instanceId) {
        this.uploadForm.typeId = node.id
        this.uploadForm.groupName = node.title
      },

      clearOnSelect: function (node, instanceId) {
        if (!node) {
          this.uploadForm.typeId = null
          this.uploadForm.groupName = null
        }
      },
      locationUrl: function (id) {
        if (id) {
          var url = this.baseURL + "diagram/index.html";
          url = url + '?id=' + id + "&t=" + new Date().getTime();
          this.modelerSrc = url
        }
        this.modelerModal = true;

      },
      locationEditUrl: function (id) {
        if (id) {
          var url = this.baseURL + "diagram/index.html";
          url = url + '?id=' + id + "&t=" + new Date().getTime()+"&edit=true";
          this.modelerSrc = url
        }
        this.modelerModal = true;

      },
      cancelModel: function () {
        this.getModelerJsonAction();
      },

      viewImage: function (id) {
        if (id) {
          var url = this.baseURL + "view/def.html?&modelId=" + id
          this.viewImageModelerTmpSrc = url;

        }
        this.viewImageModeler = true;

      },
      exportModel: function (id) {
        if (id) {
          var url = this.baseURL+"/a1bpmn/api/model/export/"+id;
          window.location.href=url
        }

      },
      busModel: function (id) {
        if (id) {
          this.$router.push({name: 'busModel', query: {t: new Date().getTime(),id:id}})
        }
      },
      sequenceModel: function (id) {
        if (id) {
          this.$router.push({name: 'sequenceModel_setting', query: {t: new Date().getTime(),id:id}})
        }
      },
      skipModel: function (id) {
        if (id) {
          this.$router.push({name: 'sequenceModel_setting', query: {t: new Date().getTime(),id:id}})
        }
      },
      urgingModel: function (id) {
        //催办插件
        if (id) {
          this.$router.push({name: 'urging_task_setting', query: {t: new Date().getTime(),id:id}})
        }
      },
      expireModel: function (id) {
        //到期提醒
        if (id) {
          this.$router.push({name: 'expire_task_setting', query: {t: new Date().getTime(),id:id}})
        }
      },
      viewModel: function (id,modelKey) {
        if (id) {
          this.$router.push({name: 'testBpm', query: {t: new Date().getTime(),id:id,modelKey:modelKey}})
        }
      },
      viewVar: function (id) {
        if (id) {
          var exist = []
          getVar(id).then((response) => {
            var data = response.data
            this.code = true;
            var html = '';
            if (data){
              if (data.length>0){
                for (var i in data) {
                  html+='<br/>';
                  if (exist.indexOf(data[i].sequenceFlow.id)==-1) {

                    html+="源节点:"+data[i].flowNode.name;
                    html+='<br/>';
                    html+="连线:"+data[i].sequenceFlow.id;
                    html+='<br/>';
                    html+="原始表达式:"+data[i].sequenceFlow.conditionExpression+"";
                    html+='<br/>';
                    html+="表达式提取变量:";
                    html+='<br/>';
                    for (var j  in  data[i].nodeList) {
                      html+='<br/>';
                      html+=data[i].nodeList[j].name;
                    }
                    exist.push(data[i].sequenceFlow.id)
                  }

                }
              }else{
                html="暂无变量"
              }
            }else{
              html="暂无变量"
            }

            this.varHtml = html;
          })
        }

      },
      versionManager: function (id, modelKey) {

        this.$router.push({name: 'versionManager', query: {t: new Date().getTime(), "modelKey": modelKey}})
      },
      openModelDialog: function () {
        var url = this.baseURL;
        url = url + "diagram/index.html" + "?t=" + new Date().getTime();
        this.modelerSrc = url
        this.modelerModal = true;
      },
      openModelDiffDialog: function () {
        this.modelerSrc = "http://diff.pangubpm.com/"
        this.modelerModal = true;
      },
      openModelUploadDialog: function () {
        this.uploadModal = true;
      },
      publishModel: function (id) {
        publishModel(id).then((response) => {
          if (response.code == 0) {
            this.$message({"duration":800,message:'发布成功',type:'success',customClass:'zZindex'});

            this.getModelerJsonAction();
          } else {
            this.$message({"duration":800,message:response.msg,type:'warning',customClass:'zZindex'});

          }

        })
      },
      queryFormCreateTime: function (e) {
        this.queryForm.createTime = e;
      },
      refreshTask: function (data) {
        if (data[0].parentId == '-1') {
          this.queryForm.typeKey = ""
          this.queryForm.type = 5
        } else {
          this.queryForm.typeKey = data[0].id;
          this.queryForm.type = 1

        }
        this.queryForm.createTime = ""
        this.queryDate = [];
        this.queryForm.whereSql = "";
        this.queryForm.page=1
        this.getModelerJsonAction()
        this.queryForm.type = 5


      },
      queryMethod: function () {
        var name = this.queryForm.name;
        var whereSql = '';
        var createTime = this.queryForm.createTime;
        if (createTime) {
          if (createTime[0]) {
            whereSql = "  CREATE_TIME_  between '" + createTime[0] + "' and " + "'" + createTime[1] + "'";
          }

        }
        this.queryForm.whereSql = whereSql;
        getModelerJson(this.queryForm).then((response) => {
          this.tableData = response.data
          this.total = parseInt(response.count);

        })

      },
      getModelerJsonAction: function () {
        getModelerJson(this.queryForm).then((response) => {

          this.tableData = response.data
          this.total = parseInt(response.count);

        })
      },
      getData: function () {
        getBpmnModelCategory().then((response) => {
          this.categoryData = response.data

        })
        this.getModelerJsonAction();

      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.getModelerJsonAction()
      },
      handleClick(val) {
        getTaskChartData({"seller_id": val}).then((response) => {
          this.chartData = response.data
          this.sellerId = val
          this.shopName = response.data.shopName
          this.chartVisible = true
        })
      },
      search() {
        this.queryForm.page = 1
        this.queryForm.type = 2
        this.queryForm.typeKey = ""
        this.queryMethod()
        this.queryForm.type = 5
      },
      reset() {
        this.queryForm.typeKey = ""
        this.queryForm.status = ""
        this.queryForm.type = 5
        this.queryForm.name = ""
        this.queryForm.modelKey = ""
        this.getData();
      }

    }

  }

</script>
<style lang="scss" scoped>
  .input_w {
    width: 40% !important;
  }
  .left-pad{
    margin-left: -11px;
  }
  .task-card {
    margin-top: 10px;
  }

  .CodeMirror {
    /* Set height, width, borders, and global font properties here */
    font-family: monospace;
    height: auto;
    color: black;
    direction: ltr;
  }

  .CodeMirror-scroll {
    height: auto;
    overflow-y: hidden;
    overflow-x: auto;
  }
</style>
